/**
 * Description: 从共享内存中读取
 * File: create.c |Time: 2021-04-07 16:54
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 1024
#define STAT_WRITE 1
#define STAT_READ 0

typedef struct {
    int status;
    char text[SHM_SIZE];
} shm_data;

int main(int argc, char *argv[])
{
    key_t shm_key = ftok("/home/b/", 'b');

    if (-1 == shm_key) {
        perror("ftok");
        return -1;
    }

    // 创建共享内存
    int shm_id = shmget(shm_key, SHM_SIZE, IPC_CREAT|0666);
    
    if (-1 == shm_id) {
        perror("shmget");
        return -1;
    }

    // 建立共享内存映射
    shm_data *buf = (shm_data *)shmat(shm_id, NULL, 0);
    
    if (buf == (shm_data *)-1) {
        perror("shmat");
        return -1;
    }

    // 读取数据
    while(1) {
        if(buf->status == STAT_WRITE){
            printf("read from shm: %s\n", buf->text);
            buf->status = STAT_READ;
        }
    }

    // 解除映射
    shmdt(buf);

    return 0;
}
